package com.retrozelda.nyanimals;

import java.io.IOException;
import java.io.InputStream;
import java.util.Hashtable;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.opengl.GLES20;
import android.opengl.GLUtils;
import android.util.Log;

public class CTextureManager 
{
	private static CTextureManager m_Instance = new CTextureManager();
	public static CTextureManager GetInstance()
	{
		return m_Instance;
	}
	
	
	
	private Hashtable<Integer, CTexture> m_Textures;
	
	private CTextureManager()
	{
		m_Textures = new Hashtable<Integer, CTexture>();
	}
	

	public CTexture GetTexture(int resource)
	{
		CTexture texture = m_Textures.get(resource);
		return texture;
	}
	
	public CTexture LoadTexture(int resource, NyanimalGLSurfaceView game)
	{
		CTexture texture = m_Textures.get(resource);
		if(texture == null)
		{
			if(game != null)
			{
				texture = LoadTexture_Internal(resource, game);
			}
			else
			{
				Log.d("CTextureManager", "SurfaceView is null and resource #" + resource + "isnt already loaded.");
			}
		}
		
		return texture;
	}

	private CTexture LoadTexture_Internal(int resource, NyanimalGLSurfaceView game)
	{
		// texture data
		CTexture newTex = new CTexture();
		int nTextureID = -1;
		int nWidth = -1;
		int nHeight = -1;
		
		// create the texture
		// NOTE: textures need to be done each time the main surface is created
		int[] textures = new int[1];
		GLES20.glGenTextures(1, textures, 0);

		// bind the texture
		nTextureID = textures[0];
		GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, nTextureID);

		// set the mip and mag
		GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MIN_FILTER, GLES20.GL_NEAREST);
		GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MAG_FILTER, GLES20.GL_LINEAR);

		// set the wrap mode
		GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_WRAP_S, GLES20.GL_REPEAT);
		GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_WRAP_T, GLES20.GL_REPEAT);

		// load the texture image
		InputStream is = game.getContext().getResources() .openRawResource(resource);
		Bitmap bitmap;
		try
		{
			bitmap = BitmapFactory.decodeStream(is);
			nWidth = bitmap.getWidth();
			nHeight = bitmap.getHeight();
		}
		finally
		{
			try
			{
				is.close();
			}
			catch (IOException e)
			{
				// Ignore.
			}
		}


		// free the texture
		GLUtils.texImage2D(GLES20.GL_TEXTURE_2D, 0, bitmap, 0);
		bitmap.recycle();
		
		// set the data
		newTex.SetData(nTextureID, nWidth, nHeight);
		return newTex;
	}
}
